﻿//Write a method that adds two positive integer numbers represented as arrays of
//digits (each array element arr[i] contains a digit; the last digit is kept in arr[0]).
//Each of the numbers that will be added could have up to 10 000 digits.


using System;

public class SumOfIntegerNumbers
{
    public static void Main()
    {
        Random rand = new Random();

        Console.Write("Enter first array length N = ");
        int length = int.Parse(Console.ReadLine());
        byte[] firstArray = new byte[length];
        PopulateArray(firstArray, rand);
        Console.WriteLine("\nFirst number is:");
        Print(firstArray);

        Console.Write("\nEnter second array length M = ");
        length = int.Parse(Console.ReadLine());
        byte[] secondArray = new byte[length];
        Console.WriteLine("\nSecond number is:");
        PopulateArray(secondArray, rand);
        Print(secondArray);

        byte[] result = SumOfIntegers((firstArray.Length >= secondArray.Length ? firstArray : secondArray), 
            (firstArray.Length < secondArray.Length ? firstArray : secondArray));
        Console.WriteLine("\nThe sum of two integers is:");
        Print(result);
    }

    private static void Print(byte[] result)
    {
        for (int i = result.Length - 1; i >= 0; i--)
        {
            if (result[i] == 0 && i == result.Length - 1)
            {
                continue;
            }
            Console.Write(result[i]);
        }
        Console.WriteLine();
    }

    private static byte[] SumOfIntegers(byte[] arrayOne, byte[] arrayTwo)
    {
        byte[] result = new byte[arrayOne.Length + 1];
        byte temp = 0;
        for (int i = 0; i < result.Length; i++)
        {
            if (i < arrayOne.Length)
            {
                if (i < arrayTwo.Length)
                {
                    temp += ((byte)(arrayOne[i] + arrayTwo[i]));
                }
                else
                {
                    temp += arrayOne[i];
                }
            }
            result[i] = (byte)(temp % 10);
            temp /= 10;
        }
        return result;
    }

    private static void PopulateArray(byte[] array, Random rand)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (i < array.Length - 1)
            {
                array[i] = (byte)rand.Next(0, 10);
            }
            else
            {
                array[i] = (byte)rand.Next(1, 10);
            }            
        }
    }
}